
package controller;

import DAO.BaseDAO;
import DAO.MetricAdminDAO;
import DAO.UserDA;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpSession;
import model.Metric;
import model.User;
import org.apache.commons.mail.EmailException;

@ManagedBean(name = "userController")
@SessionScoped
public class UserController {
    
    private User user;
    public DataModel listUsers; 
    
public UserController(){
    user = new User();
}
    
    public void saveUser() throws Exception{
        BaseDAO dao = new UserDA();
        user.setRole(2);
        dao.save(user);
        setUser(new User());
    }
    
    public String changeUser()
    {
            BaseDAO dao = new UserDA();
            dao.update(user);
            setUser(new User());
            return "consultUser.jsf";
    }
    
    public String removeUser()
    {
        User UserTemp = (User)(listUsers.getRowData());
        BaseDAO dao = new UserDA();
        dao.remove(UserTemp);
        return "#";
    }
    
    public boolean getAdmin(){
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        User u = (User) session.getAttribute("user");
        if(u.getRole()==1){
           return true; 
        }else{
            return false;
        }
    }
    
    public DataModel getListUsers()
    {
      List<User> list = new UserDA().list();
      listUsers = new ListDataModel(list);
      return listUsers;
    }
    
        public String preparaAlterar()
    {
        user = (User) (listUsers.getRowData());
        return "changeUser";
    }
    
    public void forgotPassword() throws EmailException{
        UserDA dao = new UserDA();
        List<User> list = dao.consultUser(user.getEmail());
        for(User u: list){
                user.setName(u.getName());
                user.setPassword(u.getPassword());
        }
        SendEmail se = new SendEmail();
        se.sendemailForgot(user);
        setUser(new User ());
    }
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    
    public String prepRegisterUser(){
        return "registerUser.jsf";
    }
    
    public String prepLogin(){
        return "login.jsf";
    }
    
    public String prepForgotPassword(){
        return "forgotPassword.jsf";
    }
    
    public void setNewUser()
    {
        setUser(new User());
    }
}
